package com.nbsaas.boot.controller.lock;

import com.nbsaas.boot.rest.annotations.CreateData;
import com.nbsaas.boot.rest.annotations.RecordLogData;
import com.nbsaas.boot.rest.annotations.RequiresTenant;
import com.nbsaas.boot.rest.response.ResponseObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Lock2Controller {

    private final Map<String, AtomicReference<Lock>> lockMap = new ConcurrentHashMap<>();

    private AtomicReference<Lock> getLock(String invoiceId) {
        // 获取对应单据的锁，如果没有，则新建
        return lockMap.computeIfAbsent(invoiceId, id -> new AtomicReference<>(new ReentrantLock()));
    }


    @RecordLogData
    @CreateData
    @RequiresTenant
    @PostMapping("/purchaseOrderSpec/sendBySpec")
    public ResponseObject<?> sendBySpec(@RequestBody String request) {
        ResponseObject<?> result = new ResponseObject<>();
        AtomicReference<Lock> atomicLock = getLock(request);
        Lock lock =atomicLock.get();

        // 尝试获取锁，设置超时时间，避免死锁
        boolean locked = false;
        try {
            locked = lock.tryLock(10, TimeUnit.SECONDS); // 设置超时时间为10秒
            if (locked) {
                // 处理单据
                System.out.println("处理单据: " + request);
            } else {
                // 锁获取失败，返回提示
                result = ResponseObject.error("该单据正在处理，请稍后再试");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            result = ResponseObject.error("操作被中断");
        } finally {
            if (locked) {
                lock.unlock(); // 释放锁
            }
        }
        return result;
    }

}
